<?php 
/**
 * Sales monitor funciton contains most of reporting funciton for manager and warehouse 
 * 
 */
class SalesmonitorController extends Zend_Controller_Action
{
	protected static $extRate = 5.7;
	protected static $extRateUs = 0.937; 
	
	
	protected static $targetCycle = array();
	
    public function init(){
    /**
	 *
	 *
	 */
    	self::$targetCycle = unserialize(BONUS_CYCLE_2015);  
	}
		
	/**
	 * get last week new created barcode 
	 */
	public function getLastWeekBarCodeAction(){
		$shopCode = $this->_getParam("shop");
		
		$dateBegin = Model_DatetimeHelper::getLastWeekMonday();
		$dateEnd = Model_DatetimeHelper::getThisWeekMonday();
		
		$arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateEnd);
			
	}

	
	/**
	 * this page is to staff show weekly stock take list 
	 * weekly stock take list is the one to generate the KA
	 * and adjust the qty
	 * weekly stock take is all the barcode has problem last week
	 */
	public function showWeeklyStockTakeListAction(){

		
		$shopCode = $this->_getParam("shop");
		$dateToCheck = ($this->_getParam("date")=="")?Model_DatetimeHelper::dateToday():$this->_getParam("date");
		
		if($shopCode !=""){
				
			$stockTakeWeeklyLocal = new Model_DbTable_Products_Stock_Stocktakeweeklylocal();
				
			$arrStock = $stockTakeWeeklyLocal->listStocktake($dateToCheck, $shopCode);
			
			foreach($arrStock as $key => $v){
				$arrBarcode[$key] = $v["barcode"];
			}
			
			array_multisort($arrBarcode,SORT_ASC,$arrStock);
				
			
				
			if($_POST){
					

					
			}
		}
		
		
		$this->view->shopCode = $shopCode;
		$this->view->dateToCheck = $dateToCheck;
		//var_dump($arrStock);
		$this->view->arrStock = $arrStock;		
		
	}
	
	/**
	 * this is the page to generate the weekly stock take 
	 */
	
	public function weeklyStockTakeListAction(){
		
		$shopCode = $this->_getParam("shop");
		
		$arrShopMaping = unserialize(ARR_APOS_NEW_SHOP_MAPPING);
		
		$fl = fopen("highvalue.csv","r");
		$strHigh = fread($fl,filesize("highvalue.csv"));
		$arrHighTmp = explode("\n",$strHigh);
		array_map("trim",$arrHighTmp);
		$arrHigh = array_merge($arrHighTmp,$arrHighTmp);
		echo $countArrHight = count($arrHigh);
		
		
		$dateToCheck = ($this->_getParam("date")=="")?Model_DatetimeHelper::dateToday():$this->_getParam("date");
		
		$dateBegin = Model_DatetimeHelper::adjustDays("sub", $dateToCheck, 6);
		$arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateToCheck);

		$proSk = "";
		$proSk = Model_Aposinitnew::initProStock($shopCode);
		
		
		
		$arrFinal = array();
		
		if($shopCode !=""){
			
			$stockTake = new Model_DbTable_Products_Stock_Stocktake(Zend_Registry::get('db_remoteapp'));
			foreach ($arrDate as $date){
				
				$arrStock = $stockTake->listStocktake($date, $shopCode);
				//var_dump($arrStock);
				if(!empty($arrStock) ){
				foreach($arrStock as $key => $v){
					$pos = array_search($v["barcode"],$arrFinal,true);
					if($pos === false){
						$arrFinal[]= $v["barcode"];
						$arrFinal[]= $v["sales_yest"];
						$arrFinal[]= $v["qty_sys"];
					}
					else{
						$arrFinal[$pos + 1] += $v["sales_yest"];
						$arrFinal[$pos + 2] = $v["qty_sys"];	
					}
					
				}
				}
				
				
			}
				
			echo $qtyArr = count($arrFinal)/3;
			$qtyLeft = 100 - $qtyArr;
			$keyStep = mt_rand(1, 9);
			$keyStart = mt_rand(0,30);
			
			while($qtyLeft>0 && $keyStart <$countArrHight){
				
				$result = array_search($arrHigh[$keyStart],$arrFinal,true);

				if($result === false){
					$arrFinal[] = $arrHigh[$keyStart];	
					$arrFinal[] = 0;
					//stock
					$skLine = $proSk->getStockBalance(trim($arrHigh[$keyStart]),$arrShopMaping[$shopCode]);
					if($skLine!==false){
						$arrFinal[] = (int)trim($skLine["BALANCE"]);
					}
					else{
						$arrFinal[] ="N/A";
					}
					$qtyLeft--;
					
				}
				
				$keyStart += $keyStep;
			}
		}
		
		$stockTakeWeekly = new Model_DbTable_Products_Stock_Stocktakeweekly(Zend_Registry::get('db_remoteapp'));
		$result  = array_chunk($arrFinal,3);
		
		foreach($result as $k2 => $v){
			$stockTakeWeekly->addStocktakeweekly($v[0], $v[1], $v[2], $dateToCheck,$shopCode);			
		}
		
	}
	
	/**
	 * this is the one to generat the stock take 
	 */
	public function genSalesAllAposAction(){
		
		$dateToCheck = Model_DatetimeHelper::dateYesterday();
		$proSkOld =  Model_Aposinitnew::initProBalanceAll();
		$stockTake = new Model_DbTable_Products_Stock_Stocktake(Zend_Registry::get('db_remoteapp'));
		$shopList = unserialize(ARR_APOS_NEW_SHOP_MAPPING);

		foreach ($shopList as $k => $shop){
			$arrResult = array();
			
			$inv = Model_Aposinitnew::initAposInvoice($shop);
			$invPro = Model_Aposinitnew::initAposInvPro($shop);
			
			$rowsShop = $inv->getInvoicesByDate($dateToCheck);
		
			foreach ($rowsShop as $va){
				
				$invNo = $va["INV_NO"];
				
				$prList = $invPro->getInvoiceProducts($invNo);
				
				foreach($prList as $k2 => $v){
				
					$key = array_search(trim($v["SCODE"]),$arrResult,true);
					if($key===false){
						$arrResult[] = trim($v["SCODE"]);
						$arrResult[] = (int)trim($v["QTY"]);
				
						$skLine = $proSkOld->getStockBalance(trim($v["SCODE"]), $shop);
						if($skLine!==false){
							$arrResult[] = (int)trim($skLine["BALANCE"]);
						}
						else{
							$arrResult[] ="N/A";
						}
					}
					else{
						$arrResult[$key + 1] += (int)trim($v["QTY"]);
					}
						
				}

				
			}
			
			$arrFinal = array_chunk($arrResult,3);
			
			foreach($arrFinal as $k2 => $v2){
				if($v2[0]!="INSTALLATION" && $v2[0]!="PHONEREPAIR" && $v2[0]!="CN" && $v2[0]!="SERVICE" && $v2[0]!="INSTALL" && $v2[0]!="PARTSSALES"   ){
						
					$stockTake->addStocktake($v2[0],$v2[1],$v2[2],null,Model_DatetimeHelper::dateToday(),null,$shop,null);
			
				}
			}
			
		
		}

		
	}
	
	/**
	 * generate the sales by date 
	 */
	public function genSalesAposByDateAction(){

		$shop = $this->_getParam("shop");
		$dateToCheck = Model_DatetimeHelper::dateYesterday();
		$dateBegin = Model_DatetimeHelper::adjustDays("sub", $dateToCheck,1);
		
		$arrShopMaping = unserialize(ARR_APOS_NEW_SHOP_MAPPING);
		
		
		
		//get Product Stock
		
		$proSk = Model_Aposinitnew::initProStock($shop);
		
		//
		$stockTake = new Model_DbTable_Products_Stock_Stocktake(Zend_Registry::get('db_remoteapp'));
		
		//init the object
			$invOld = Model_Aposinitnew::initAposInvoice($shop);
			$invPro = Model_Aposinitnew::initAposInvPro($shop);

		$rowsDateBegin = $invOld->getInvoicesByDate($dateBegin); 
		$rowsDateCheck = $invOld->getInvoicesByDate($dateToCheck);

		$arrResult = array();
		
		foreach($rowsDateBegin as  $va){
		
			$invNo = $va["INV_NO"];
		
			$prList = $invPro->getInvoiceProducts($invNo);
		
			foreach($prList as $k2 => $v){
		
		
				$key = array_search(trim($v["SCODE"]),$arrResult,true);
				if($key===false){
					$arrResult[] = trim($v["SCODE"]);
					$arrResult[] = (int)trim($v["QTY"]);
		
					$skLine = $proSk->getStockBalance(trim($v["SCODE"]),$arrShopMaping[$shop]);
					if($skLine!==false){
						$arrResult[] = (int)trim($skLine["BALANCE"]);
					}
					else{
						$arrResult[] ="N/A";
					}
				}
				else{
					$arrResult[$key + 1] += (int)trim($v["QTY"]);
				}
					
			}
		
		}
		
		foreach($rowsDateCheck as  $vb){
		
			$invNo = $vb["INV_NO"];
		
			$prList = $invPro->getInvoiceProducts($invNo);
		
			foreach($prList as $k3 => $v){
		
		
				$key = array_search(trim($v["SCODE"]),$arrResult,true);
				if($key===false){
					$arrResult[] = trim($v["SCODE"]);
					$arrResult[] = (int)trim($v["QTY"]);
		
					$skLine = $proSk->getStockBalance(trim($v["SCODE"]),$arrShopMaping[$shop]);
					if($skLine!==false){
						$arrResult[] = (int)trim($skLine["BALANCE"]);
					}
					else{
						$arrResult[] ="N/A";
					}
				}
				else{
					$arrResult[$key + 1] += (int)trim($v["QTY"]);
				}
					
			}
		
		}		
		
		$arrFinal = array_chunk($arrResult,3);
		
		foreach($arrFinal as $k2 => $v2){
		
			$stockTake->addStocktake($v2[0],$v2[1],$v2[2],null,Model_DatetimeHelper::dateToday(),null,$shop,null);
		}		
		

		
		
	}
	
	/**
	 * This is the page for warehouse to check 
	 * 1. staff login 
	 * 2. cash account 
	 * 3. sales
	 * 4. reset the shop password
	 */
	
	public function yesterdaySummaryAction(){
		
		date_default_timezone_set('Australia/Melbourne');

		
		
		$attRecord = new Model_DbTable_Roster_Attnrecord();
		$staffs = new Model_DbTable_Roster_Stafflogindetail();
		$skTake = new Model_DbTable_Products_Stock_Stocktakelocal();
		$skTakeWeekly = new Model_DbTable_Products_Stock_Stocktakediflocal();
		$caOpening = new Model_DbTable_Cashaccountopening();
		$caClosing = new Model_DbTable_Cashaccountclosing();
		
		$auto = $this->_getParam("auto");
		

		$dateToCheck = Model_DatetimeHelper::dateToday();
		
		$anotherDay = $this->_getParam("date");
		if($anotherDay!=""){
			$dateToCheck = $this->_getParam("date");
		}
		$dateToCheckYesterday = Model_DatetimeHelper::adjustDays("sub", $dateToCheck,1);
		
		$this->view->dateToCheck = $dateToCheck;
		$this->view->dateToCheckYesterday = $dateToCheckYesterday;
		
		
		
		
		
		$arrShopHead = unserialize(ARR_SHOP_ACTIVE);
		
		$arrRes = array();
		
		foreach ($arrShopHead as $v){
			if($v == "ADPC" || $v == "CLPC" || $v == "CLIC" || $v == "WLIC"){
				
				date_default_timezone_set('Australia/Adelaide');
			}
			else{
				
				date_default_timezone_set('Australia/Melbourne');
			}
			$tmpArr = array();
			
			//Shop Name 
			
			// Attendance Record
			
			
			$tmpArr[0] = $v;
			
			//Latest Time Yesterday Closing
			
			$resultYesterday = $attRecord->getRecordByShop(Model_EncryptHelper::sslPassword(trim($v)),$dateToCheckYesterday,$dateToCheckYesterday);
			if(!$resultYesterday){
					
				$tmpArr[1]= "No Record";
			}
			else{
				$vYes=end($resultYesterday);
					
				$tmpArr[1] = date("H :i",$vYes["ti"]);
			}
			// Detai Person
				$tmpArr[2] = "";
			$tStaList = $attRecord->getOndutyByDateByShop($v, $dateToCheckYesterday);
			if(!empty($tStaList)){
				
				foreach($tStaList as $k1 =>$v1){
			
					//echo $v["sti"];
					$stDetail = $staffs->getDetail($v1["sti"]);
					$tmpArr[2] .= ucwords(Model_EncryptHelper::getSslPassword($stDetail["n"]));
					$tmpArr[2] .= "(".ucwords($stDetail["ni"]).")";
					$arrRecord = $attRecord->getFirstOnLastOffDuty($v1["sti"], $dateToCheckYesterday, Model_EncryptHelper::sslPassword($v));
					//var_dump($arrRecord);
					$begin = "[NoRecord]";
					$end = "";
			
					if( $arrRecord[0] != "" ){
						$begin = date("H:i",$arrRecord[0]);
					}
					if( $arrRecord[1] != "" ){
						$end = date("H:i",$arrRecord[1]);
					}
					$tmpArr[2] .= " {$begin} to {$end}<br/>";
				}
				}
			
			//TODay Attendance
				//Latest Time Yesterday Closing
					
				$resultToday = $attRecord->getRecordByShop(Model_EncryptHelper::sslPassword(trim($v)),$dateToCheck,$dateToCheck);
				if(!$resultToday){
						
					$tmpArr[3]= "No Record";
				}
				else{
					$vTo=$resultToday[0];
						
					$tmpArr[3] = date("H :i",$vTo["ti"]);
				}
				// Today Detail
					$tmpArr[4] = "";
					
					$tStaList2 = $attRecord->getOndutyByDateByShop($v, $dateToCheck);
					if(!empty($tStaList2)){
					
						foreach($tStaList2 as $k2 =>$v2){
								
							//echo $v["sti"];
							$stDetail = $staffs->getDetail($v2["sti"]);
							$tmpArr[4] .= ucwords(Model_EncryptHelper::getSslPassword($stDetail["n"]));
							$tmpArr[4] .= "(".ucwords($stDetail["ni"]).")";
							$arrRecord = $attRecord->getFirstOnLastOffDuty($v2["sti"], $dateToCheck, Model_EncryptHelper::sslPassword($v));
							//var_dump($arrRecord);
							$begin = "[NoRecord]";
							$end = "";
								
							if( $arrRecord[0] != "" ){
								$begin = date("H:i",$arrRecord[0]);
							}
							if( $arrRecord[1] != "" ){
								$end = date("H:i",$arrRecord[1]);
							}
							$tmpArr[4] .= " {$begin} to {$end}<br/>";
						}
					}
			
			
			
			$tmpArr[5] = "";
			
			$caClsR2 = $caClosing->getActiveClosingByDate($v,$dateToCheckYesterday);
			if(!$caClsR2) {
				$tmpArr[5] ='<img src="/im/error2.jpg" />';
			}
			else{$tmpArr[5] ='<img src="/im/clicked.jpg" />';
			}
			
			$tmpArr[6] = "";
				
			$caOpeR2 = $caOpening->getActiveOpeningByDate($v,$dateToCheck);
			if(!$caOpeR2) {
				$tmpArr[6] = '<img src="/im/error2.jpg" />';
			}
			else{$tmpArr[6] = '<img src="/im/clicked.jpg" />';
			}
				
			
			$tmpArr[7] = "[NO Record]";
			
			if($caClsR2) {
				$tmpArr[7] = $caClsR2[0]["total_net_sales_close"];
			}
			
			//echo "date".$dateToCheck;
			$arrProducts = $skTake->listStocktake($dateToCheck,$v);
			$tmpArr[8] = count($arrProducts);
			$tmpArr[9] = $ifSubmit = $skTake->ifSubmitActual($dateToCheck,$v);
			$tmpArr[10] = $ifSubmitWeekly = $skTakeWeekly->ifSubmitActual($dateToCheck, $v);
			$tmpArr[11] = ($caClsR2)?$caClsR2[0]['sync_status']:true;
			$tmpArr[12] = ($caOpeR2)?$caOpeR2[0]['check_dvr']:false;
			//var_dump($arrProducts);
			//$tmpArr = array($v,count($arrProducts),$ifSubmit);
			if($caOpeR2) {
				$tmpArr[13] = $caOpeR2[0]['time_record_open'];
			}
			else{$tmpArr[13] = 'Null';
			}
			
			$arrRes[]=$tmpArr;
		
		}
		//echo "<pre>";
		//var_dump($arrRes);
		//echo "</pre>";
		
		$this->view->arrRes = $arrRes;
		if($auto == 'yes'){
			$this->view->auto = true;
			$this->renderScript('/salesmonitor/yesterday-summary-auto.phtml');
			
		}
	}
	
	
	/**
	 * daily sale record for regenerate stock take 
	 */
	public function genShopSalesOldAction(){
		
		$arrShopMaping = unserialize(ARR_APOS_NEW_SHOP_MAPPING);
		
		$shop = $this->_getParam("shop");
		echo $dateToCheck = Model_DatetimeHelper::dateYesterday();
		//$dateToCheck = '2013-06-03';
		$anotherDay = $this->_getParam("date");
		if($anotherDay!=""){
			$dateToCheck = Model_DatetimeHelper::adjustDays("sub",$this->_getParam("date"),1);
		}
		$dateLog = Model_DatetimeHelper::adjustDays("add",$dateToCheck,1);
		
		$invOld = Model_Aposinitnew::initAposInvoice($shop);
		$proOld = Model_Aposinitnew::initAposInvPro($shop);
		$rowsOld = "";
		
		$proSkOld = new Model_DbTable_Apos_Stock_Balanceold(Zend_Registry::get('db_allapos'));
		$stockTake = new Model_DbTable_Products_Stock_Stocktake(Zend_Registry::get('db_remoteapp'));
		$stockTake->cleanListByDate($dateLog,$shop);
		
		//
		$rowsOld = $invOld->getInvoicesByDate($dateToCheck);
		
		$arrResult = array();
	
		foreach($rowsOld as  $vaOld){
	
			$invNo = $vaOld["INV_NO"];
	
			$prList = $proOld->getInvoiceProducts($invNo);
	
			foreach($prList as $k2 => $v){
	
	
				$key = array_search(trim($v["SCODE"]),$arrResult,true);
				if($key===false){
					$arrResult[] = trim($v["SCODE"]);
					$arrResult[] = (int)trim($v["QTY"]);
	
					$skLine = $proSkOld->getStockBalance(trim($v["SCODE"]), $arrShopMaping[$shop]);
					if($skLine!==false){
						$arrResult[] = (int)trim($skLine["BALANCE"]);
					}
					else{
						$arrResult[] ="N/A";
					}
				}
				else{
					$arrResult[$key + 1] += (int)trim($v["QTY"]);
				}
					
			}
	
		}
	
		$arrFinal = array_chunk($arrResult,3);
		echo count($arrFinal);
		foreach($arrFinal as $k2 => $v2){
			if($v2[0]!="INSTALLATION" && $v2[0]!="PHONEREPAIR" && $v2[0]!="CN" && $v2[0]!="SERVICE" && $v2[0]!="INSTALL" && $v2[0]!="PARTSSALES"   ){
			$stockTake->addStocktake($v2[0],$v2[1],$v2[2],null,$dateLog,null,$shop,null);
			}
		}
	}
	
	/**
	 * daily generate stock take 
	 */
	
	public function genShopSalesNewAction(){
		
		$arrShopMaping = unserialize(ARR_APOS_NEW_SHOP_MAPPING);
		
	
		$shop = $this->_getParam("shop");
		echo $dateToCheck = Model_DatetimeHelper::dateYesterday();
		//$dateToCheck = '2013-06-03';
		$anotherDay = $this->_getParam("date");
		if($anotherDay!=""){
			$dateToCheck = Model_DatetimeHelper::adjustDays("sub",$this->_getParam("date"),1);
		}
		$dateLog = Model_DatetimeHelper::adjustDays("add",$dateToCheck,1);
		
		$invNew = Model_Aposinitnew::initAposInvoice($shop);
		$proNew = Model_Aposinitnew::initAposInvPro($shop);
		$rowsNew = "";
	
		$proSkNew = Model_Aposinitnew::initProBalanceAll();
		$stockTake = new Model_DbTable_Products_Stock_Stocktake(Zend_Registry::get('db_remoteapp'));
		$stockTake->cleanListByDate($dateLog,$shop);
		
		//
		$rowsNew = $invNew->getInvoicesByDate($dateToCheck);
	
		$arrResult = array();
	
		foreach($rowsNew as  $vaNew){
	
			$invNo = $vaNew["INV_NO"];
	
			$prList = $proNew->getInvoiceProducts($invNo);
	
			foreach($prList as $k2 => $v){
	
	
				$key = array_search(trim($v["SCODE"]),$arrResult,true);
				if($key===false){
					$arrResult[] = trim($v["SCODE"]);
					$arrResult[] = (int)trim($v["QTY"]);
	
					$skLine = $proSkNew->getStockBalance(trim($v["SCODE"]),$arrShopMaping[$shop]);
					if($skLine!==false){
						$arrResult[] = (int)trim($skLine["BALANCE"]);
					}
					else{
						$arrResult[] ="N/A";
					}
				}
				else{
					$arrResult[$key + 1] += (int)trim($v["QTY"]);
				}
					
			}
	
		}
	
		$arrFinal = array_chunk($arrResult,3);
		echo count($arrFinal);
		foreach($arrFinal as $k2 => $v2){
			if($v2[0]!="INSTALLATION" && $v2[0]!="PHONEREPAIR" && $v2[0]!="CN" && $v2[0]!="SERVICE" && $v2[0]!="INSTALL" && $v2[0]!="PARTSSALES"   ){
			$stockTake->addStocktake($v2[0],$v2[1],$v2[2],null,$dateLog,null,$shop,null);
			}
		}
	}

	/**
	 * report function to report which shop do more invoice on which hour
	 */
	public function topHoursAction(){
		
		$dateBegin = $this->_getParam("date");
		$weeks = $this->_getParam("week");
		$shop =  $this->_getParam("shop");

		$dayDiff = $weeks*7-1;
		
		//$dateBegin = "2013-04-01";
		$dateEnd = Model_DatetimeHelper::adjustDays("add", $dateBegin,$dayDiff);
		//$dateToCheck = $dateBegin;
		
		$arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateEnd);
		$invOld = Model_Aposinitnew::initAposInvoice($shop);
		
		$arrInvoices = array();
		foreach ($arrDate as $dateToCheck){
			
			$invArr = $invOld->getInvoicesByDate($dateToCheck);	
			$arrTime = $invOld->getInvoiceNoArray($invArr);	
			
			foreach($arrTime as $dow => $tods){

				foreach($tods as $hod => $value){
					if(isset($arrInvoices[$dow][$hod])){
						$arrInvoices[$dow][$hod] +=$value;	
					}
					else{
						$arrInvoices[$dow][$hod] = $value;
					}
					
				}	
			}
		} 
		
		$this->view->arrInvoice = $arrInvoices;
		$this->view->arrDate = $arrDate;
		$this->view->week = $weeks;
		//var_dump($arrInvoices);
	}	

	
	/**
	 * show diff of weekly stock take 
	 */
	public function showWeeklyStockTakeDiffAction(){
		
		$shop = $this->_getParam("shop");
		$dateToCheck = $this->_getParam("date"); 
		$this->view->shopCode = $shop;
		$dateToday = ($dateToCheck=="")?Model_DatetimeHelper::dateToday():$dateToCheck;
		$this->view->dateToCheck = $dateToday;
		$afterPost = false;
		
		$stockTake = new Model_DbTable_Products_Stock_Stocktakediflocal();
		

		$staffDetail = new Model_DbTable_Roster_Stafflogindetail();
		
		//var_dump($stLine);
		
		
		if($_POST){
			if(isset($_POST['btn_addcode'])){
				$barcode = trim($_POST["add_code"]);
				
				if(trim($barcode)!=""){
					
					//d($shop);

					$qtySys = Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/get-current-stock/barcode/".$barcode."/shop/".$shop);
					$stockTake->addStocktake($barcode, $qtySys,null, $dateToday,null, $shop,null);
				}

				
			}
			else{
				
				$res = $staffDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha(trim($_POST["att_pwd"])));
				//var_dump($res);
				if($res!==false){
						
					foreach($_POST["qty_act"] as $key => $v){
						$qact = $v;
						if($v==""){
							$qact = null;
						}
				
						$stockTake->updateActStock($key, $qact,$res['id']);
					}
				
					$afterPost =true;
				
				}
				else{
					echo "<h1>Incorrect Password,Result Will Not Save!!Click \"Back To Return\"</h1>";
				
				}				
				
				
				
			}
			
	
		}
		

		
		$stLine = $stockTake->listStocktake($dateToday,$shop);
		
		$this->view->arrStock = $stLine;
		
		
		if($afterPost){
			
			$this->renderScript('/salesmonitor/send-weekly-stocktake-result.phtml');
		}
		
		
	}
	/**
	 * this is the page to find the diffence of daily stock take and put into weekly stock take 
	 */
	public function weeklyStockTakeDiffAction(){
		
		
		$shop = $this->_getParam("shop");
		$this->view->shopCode = $shop;
		
		
		
		$arrShopMaping = unserialize(ARR_APOS_NEW_SHOP_MAPPING);
		
		$dateBegin = Model_DatetimeHelper::getLastWeekMonday();
		$dateEnd = Model_DatetimeHelper::getLastWeekSunday();	
		$dateToday = Model_DatetimeHelper::dateToday();
		
		$proSk = Model_Aposinitnew::initProStock($shop);
		
		$arrSummary = array();
		
		 
		if($shop!=""){

			$stockTake = new Model_DbTable_Products_Stock_Stocktake(Zend_Registry::get('db_remoteapp'));
			$arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateEnd);
			
			$sTDiff = new Model_DbTable_Products_Stock_Stocktakedif(Zend_Registry::get('db_remoteapp'));
			$sTDiff->delStockTakeByShopByDate($dateToday,$shop);
			
			foreach($arrDate as $dateToCheck){
				
				$difRes = $stockTake->listDiff($dateToCheck, $shop);
				foreach($difRes as $k => $v){
					$key = array_search(trim($v["barcode"]),$arrSummary,true);
					if($key === false){
							
						$arrSummary[] = trim($v["barcode"]);
					}
					
				}
				
			}
			
			var_dump($arrSummary); // out put of array summary
			
			foreach($arrSummary as $barcode){

				$balance = 0;
			$skLine = $proSk->getStockBalance(trim($barcode), $arrShopMaping[$shop]);
					if($skLine!==false){
						$balance = (int)trim($skLine["BALANCE"]);
					}				
			//$sTDiff->addStocktake($barcode, $qtySys, $qtyAct, $dateTake, $timeUpload, $location, $staffName);
				$sTDiff->addStocktake(trim($barcode),$balance,null,$dateToday,null,$shop,null);
			}
			
			
			//put array summary into list 
			//get current onhand from apos and list in the sytem
			
			
		}
		
	}
	/**
	 * this is to check the stock take result and show the abnormal
	 */
	public function checkStockTakeResultAction(){
		
		if($_POST){
				
			$this->_redirect("/salesmonitor/check-stock-take-result/shop/".$_POST["shopcode"]."/date_begin/".$_POST["date_begin"]."/date_end/".$_POST["date_end"]);	
				
		}
		
		$shop = $this->_getParam("shop");
		$this->view->shopCode = $shop;
		$dateBegin = $this->_getParam("date_begin");
		$dateEnd = $this->_getParam("date_end");
		
		$arrRes = array();
		$arrSummary = array();
		$arrList = array();
		
		if($shop!="" && $dateBegin!="" && $dateEnd !="" ){
			
		$stockTake = new Model_DbTable_Products_Stock_Stocktakelocal();
		$arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateEnd);

		$passLevel = 3;
		
		foreach($arrDate as $dateToCheck){
			
			$difRes = $stockTake->listDiff($dateToCheck, $shop);
			$submitCheck = $stockTake->ifSubmitActual($dateToCheck, $shop);
			$dateList = $stockTake->listStocktake($dateToCheck,$shop);
			$arrList[]= $dateList;
			
			$tmpArr = array();
			$tmpArr[0] = $dateToCheck;
			$tmpArr[1] = $submitCheck;

			$barCodeArr = array();
			
			foreach($difRes as $k => $v){

				$key = array_search(trim($v["barcode"]),$arrSummary,true);
				
				
				if($key === false){
					
					$arrSummary[] = trim($v["barcode"]);
					$barCodeArr[] = trim($v["barcode"]);
					$arrSummary[] = $v["qty_act"] - $v["qty_sys"];
					$arrSummary[] = $v["date_take"];
					$arrSummary[] = $v["date_take"];
					$arrSummary[] = 1; 
					$arrSummary[] = 0;
						
				}else{
					//if(trim($v["barcode"])=="SPIPHONE5"){echo "FD";}
					
					if( ($v["qty_act"] - $v["qty_sys"]) != $arrSummary[$key + 1]){
						
						$arrSummary[$key + 3] = $v["date_take"];
						$arrSummary[$key + 4] = 1;
						$arrSummary[$key + 5] += 1;
						$arrSummary[$key + 1] = $v["qty_act"] - $v["qty_sys"];
						
					}
					else{
						
						$arrSummary[$key + 4] += 1;
					}
					
				}
				
			}
			$tmpArr[2] = $barCodeArr;	
			$arrRes[] = $tmpArr;
			
		}
		
		}
		$this->view->arrRes = $arrRes;
		$this->view->arrSummary = array_chunk($arrSummary,6);
		$this->view->arrList = $arrList;
	}
	
	/**
	 * using this one to create KA
	 */
	public function exportStockTakeResultAction(){
		
		$fileName = "";
		$shop= $this->_getParam("shop");
		$date = $this->_getParam("date");
		
		$products = Model_Aposinitnew::initProDes();
		
		
		$fileName = $shop."-".$date;
		$fileNameDetail = $shop."-".$date."-Detail";
		//$fl = fopen($fileName,"a");
		$arrRes = array();	
		$stDif = new Model_DbTable_Products_Stock_Stocktakediflocal(Zend_Registry::get('db_remoteapp'));
		$res = $stDif->listDiff($date, $shop);
	
		//var_dump($res);
		foreach($res as $line){
			$desLine = $products->getAposDes($line["barcode"]);
			$arrTmp = array($line["barcode"],$line["qty_act"] - $line["qty_sys"],$desLine["APRICE"]);
			//fputcsv($fl, $arrTmp);
			$arrRes[] = $arrTmp;
		}	
		// add into it 
		$qtyAdj = new Model_Products_Adjustment(Zend_Registry::get('db_remoteapp'));
		$adjList = $qtyAdj->listTempKaByShop($shop);
		
		$adjFileName = "RA-". $shop."-".$date;
		$adjFileNameDetail = "RA-". $shop."-".$date."-Detail"; 
		
		//d($adjList);
		$arrQtyAdj = array();
		foreach($adjList as $k => $v){
			
			$desLine = $products->getAposDes($v["code_product"]);
			$price = $desLine['APRICE'];
			if($v['qty_adjust']!=0){	
				$arrQtyAdj[] = array($v['code_product'],$v['qty_adjust'],$price);	
			}
		}
		
		$arrRes = array_merge($arrRes,$arrQtyAdj);
		
		$fl = new Model_Fileshandler();
		//$fl->exportWeeklyStResult($arrQtyAdj, $adjFileName);
		//$fl->exportWeeklyStResultDetail($arrQtyAdj, $adjFileNameDetail);
		$fl->exportWeeklyStResult($arrRes, $fileName);
		$fl->exportWeeklyStResultDetail($arrRes, $fileNameDetail);
		fclose($fl);
	}
	
	/**
	 * using this one to create all shop KA on every tuesday
	 */
	public function exportStockTakeCircleAction(){
		set_time_limit(0);
		$date = Model_DatetimeHelper::getThisWeekMonday();
		
		
		ob_start();
		
		$shopArr = unserialize(ARR_SHOP_ACTIVE);
		

			foreach($shopArr as $shop){
				echo $str="http://localhost/salesmonitor/export-stock-take-result/shop/".$shop."/date/".$date;
				echo "<br />";
				$res = Model_System_Downloadhelper::downloadUrl($str);
				//sleep(1);
				echo $res;
				ob_flush();
				flush();
				//echo $date;
			}		
	}
	
	/**
	 * who still did not finish daily stock take  on 3 pm in the afternoon
	 */
	public function dailyStockTakeNotFinishAction(){

		//clean table for all the shop 
		//$date = Model_DatetimeHelper::dateToday();
		$shopHead = $this->_getParam("shop");
		$getDate = $this->_getParam("date");
		$date = ($getDate!="")?$this->_getParam("date"):Model_DatetimeHelper::dateToday();;
		//or date today
		$skTableB = new Model_DbTable_Products_Stock_Tableblocal();
		$skTableB->deleteAll($shopHead);
		
		
		$skTake = new Model_DbTable_Products_Stock_Stocktakelocal();
		// check table A finish or not 
		$ifSubmit = $skTake->ifSubmitActual($date, $shopHead);
		
		if(!$ifSubmit){
			$list = $skTake->listStocktake($date, $shopHead);
			
			foreach($list as $key =>$value){
					$skTableB->addTableb($value["barcode"], $shopHead);
			}
		}
		
		//finish do nothing 
		
		//not finish copy to table B
		
	}
	
	/**
	 * page to cirle to 20+ shops to find who not finish daily stock take 
	 */
	public function dailyNotFinishCircleAction(){
		
		set_time_limit(0);
		ob_start();
		

		$shopArr = unserialize(ARR_SHOP);
		//$shopArr=array("HPIC");
			foreach($shopArr as $shop){
				echo $str="http://localhost/salesmonitor/daily-stock-take-not-finish/shop/".$shop;
				echo "<br />";
		
				$res = Model_System_Downloadhelper::downloadUrl($str);
				//sleep(1);
				echo $res;
				ob_flush();
				flush();
				//echo $date;
			}
	}

	/**
	 * this is the funcion to patch table B 
	 */
	public function patchTablebCircleAction(){
		
		set_time_limit(0);
		ob_start();
		
		
		$shopArr = unserialize(ARR_SHOP); 
		//$shopArr=array("HPIC");
		foreach($shopArr as $shop){
			echo $str="http://localhost/salesmonitor/patch-tableb/shop/".$shop;
			echo "<br />";
		
			$res = Model_System_Downloadhelper::downloadUrl($str);
			//sleep(1);
			echo $res;
			ob_flush();
			flush();
			//echo $date;
		}		
		
	}


	/**
	 * Add After Qty Adjustment 
	 * Anything Not Adjusted , should not be input into today's stock take adjustment (Daily?<- Weekly?)
	 * if in the list which is possible, alret me 
	 * run on lunch time every day
	 */
	public function removeQtyAdjustAction(){
		// list all unconfirmed , temp , not canceled 
		$qtyAdj = new Model_Products_Adjustment();
		$qaList = $qtyAdj->listAllNotAdjusted();
		$dailySk = new Model_DbTable_Products_Stock_Stocktakelocal();
		// get into today's stock take list 
		foreach($qaList as $item){
			
			$isExist = $dailySk->ifBarcodeExist(Model_DatetimeHelper::dateToday(), $item['code_shop'], $item['code_product']);
			
			if($isExist){
			$mail = new Model_Emailshandler();
			$mail->sendNormalEmail("eco3@phonecollection.com.au","Conflict",var_dump($isExist));	
				
			}
		}
		
	}
	/**
	 * table B is the stock take not finished part
	 * it will be add into second day stock take
	 */
	public function patchTablebAction(){
		
		$shopHead = $shop =  $this->_getParam("shop");
		$date = Model_DatetimeHelper::dateToday();
		//or date today
		$tableB = new Model_DbTable_Products_Stock_Tableblocal();
		$skTake = new Model_DbTable_Products_Stock_Stocktakelocal();
		
		$tList = $tableB->listByShop($shopHead);
		$sList = $skTake->listStocktake($date, $shopHead);
		
		$arrTaBarcode = array();
		$arrSkBarcode = array();
		
		//$arrShopMaping = unserialize(ARR_APOS_NEW_SHOP_MAPPING);
		
		
		
		foreach($tList as $tb){
			$arrTaBarcode[] = $tb["barcode"];	
		}
		
		foreach($sList as $sk){
			$arrSkBarcode[] = $sk["barcode"];
		}
		
		$arrRes = array_diff($arrTaBarcode, $arrSkBarcode);
		
		//var_dump($arrRes);
		
		//$proSk = Model_Aposinit::initProStock($shop);
		
		
	
		$skQty = $skTake->listStocktake(Model_DatetimeHelper::dateToday(), $shop);
		$maxQty = 40 - count($skQty);
		
		if($maxQty >0){
			$cot = 0;
		foreach($arrRes as $bcode){
						
			$qty = Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/get-current-stock/barcode/".$bcode."/shop/".$shopHead);
			//$skTake->addStocktake($barcode, $salesYest, $qtySys, $qtyAct, $dateTake, $timeUpload, $location, $staffName);
			if($cot < $maxQty )
			{	
			$skTake->addStocktake($bcode,0,(int)$qty,null,Model_DatetimeHelper::dateToday(),null,$shop,null);
			$cot++;	
			}
		}
		}
		
		//for this barcode sales is 0, otherwise it will be in today's list
	}
	
	/**
	 * calcualte shop target 
	 */
	public function calShopTargetAction(){
		
		$caClose = new Model_DbTable_Cashaccountclosing();
		//$sf = new Model_DbTable_Target_Shopfomula();
		
		//$sfList = $sf->listAll();
		
		//$shopArr = array("ADPC","BBPC","BHPC","BSPC","BSIC","CBPC","CLPC","EPPC","KCPC","NLPC","PMPC","SLIC","WBPC","WBIC","WLIC","WGIC","WGPC","CSIC","CLIC","DCIC","PMIC","BSXP","FGIC","HPIC");
		$shopArr = unserialize(ARR_SHOP);
		
		
		$target = new Model_DbTable_Target_Weeklytarget();
		$shopf = new Model_DbTable_Target_Shopfomula(); 
		
		$sfList = $shopf->listAll();
		
		
		$dateBegin = "2014-02-03";
		$dateEnd = "2014-03-02";
		
		$arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateEnd);
		$weeks = count($arrDate)/7;
		//echo $weeks;
		$arrWeeks = array();
		$arrRes = array();
		for($i=0;$i<$weeks;$i++){
			$arrWeeks[$i]["date_begin"] = Model_DatetimeHelper::adjustWeeks("add", $dateBegin, $i);
			$arrWeeks[$i]["date_end"] = Model_DatetimeHelper::adjustWeeks("add", Model_DatetimeHelper::adjustDays("add",$dateBegin,6), $i); 
		}
		//var_dump($arrWeeks);
		
		foreach($sfList as $row){
			
			$shop = $row["shop_code"];
			$staffID = $row["id_staff"];
			
			$tmpArr = array();
			$tmpArr[] = $shop; //shop 
			$monthSum = 0;
			$totalBonus = 0;
			$tmpArr[]= 0;
			foreach($arrWeeks as $k => $v){
				  //
				  $tmpArr[] = $weekSum = $caClose->getWeeklyAPOSSummaryShop($shop,$v["date_begin"], $v["date_end"]);	
				  
				  $tarLine = $target->getWeeklyTargetByShopByDate($shop,$v["date_begin"]);
				 // var_dump($tarLine);
				  
				  $tmpArr[] = $weekBonus = $shopf->calBonus($staffID,$shop,$weekSum,$tarLine["target"]);
				  $monthSum += $weekSum; 	
				  $totalBonus +=$weekBonus;
			}
			$tmpArr[] = $monthSum; // monthly total
			$tmpArr[] = $tarLine["target"]; // weekly 
			$tmpArr[] = $tarLine["target"]*$weeks; // monthly target
			$tmpArr[] = $totalBonus;
			$tmpArr[] = $staffID;
			// bonus
			$arrRes[] = $tmpArr;
		}
		
		$this->view->arrWeek = $arrWeeks;
		$this->view->arrRes = $arrRes;
		$this->view->dateBegin = $dateBegin;
		$this->view->dateEnd = $dateEnd;
		
		//var_dump($arrRes);
		
		//$res = $caClose->getWeeklyAPOSSummaryShop("BHPC", "2013-07-22","2013-07-28");
		
		//var_dump($res);
	}
	
	/**
	 * this will be send out every monday morning to tell manager if the target has been met 
	 */
	public function calShopTargetManagerAction(){
		
		$idManager = 0;
		$idManager = $this->_getParam("mgr");
		$ifEmail = $this->_getParam("email");
		
		$staffKPI = array();
		
		$arrMgrEmail = unserialize(ARR_MANAGER_EMAIL);
		
		$caClose = new Model_DbTable_Cashaccountclosing(Zend_Registry::get('db_remoteapp'));
		
		$target = new Model_DbTable_Target_Weeklytarget(Zend_Registry::get('db_remoteapp'));
		$shopf = new Model_DbTable_Target_Shopfomula(Zend_Registry::get('db_remoteapp'));
		
		
		$ts = new Model_DbTable_Roster_Timesheet(Zend_Registry::get('db_remoteapp'));
		$sales = new Model_DbTable_Roster_Salesmandetail(Zend_Registry::get('db_remoteapp'));
		
		//$sfList = $shopf->listAll();
		if($idManager == 'all'){$idManager = 4;}
		$sfList = $shopf->listShopByManager($idManager);
		
		$arrCircle = $this->whichCircle(Model_DatetimeHelper::dateYesterday());
		
		$dateBegin = $arrCircle[0];
		$dateEnd = $arrCircle[1];
		
		$arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateEnd);
		$weeks = count($arrDate)/7;
		//echo $weeks;
		$arrWeeks = array();
		$arrRes = array();
		for($i=0;$i<$weeks;$i++){
			$arrWeeks[$i]["date_begin"] = Model_DatetimeHelper::adjustWeeks("add", $dateBegin, $i);
			$arrWeeks[$i]["date_end"] = Model_DatetimeHelper::adjustWeeks("add", Model_DatetimeHelper::adjustDays("add",$dateBegin,6), $i);
		}
		//var_dump($arrWeeks);
		
		foreach($sfList as $row){
				
			$shop = $row["shop_code"];
			$staffID = $row["id_staff"];
				
			$tmpArr = array();
			$tmpArr['shop'] = $shop; //shop
			$monthSum = 0;
			$totalBonus = 0;
			foreach($arrWeeks as $k => $v){
				//
				$tmpArr[] = $weekSum = $caClose->getWeeklyAPOSSummaryShop($shop,$v["date_begin"], $v["date_end"]);
		
				$tarLine = $target->getWeeklyTargetByShopByDate($shop,$v["date_begin"]);
				// var_dump($tarLine);

				$monthSum += $weekSum;
		
				
				
				//cal Staff KPI
				
				
				if($v["date_end"] < Model_DatetimeHelper::dateToday()){
					
					$intDateBegin = Model_DatetimeHelper::tranferToInt($v['date_begin']);
					$intDateEnd = Model_DatetimeHelper::tranferToInt($v['date_end']);
					$invApos = Model_Aposinitnew::initAposInvoice($shop);
					
					$salesList = $invApos->getSaleManSales($v['date_begin'],$v['date_end']);
						foreach($salesList as $key => $value){
						
							$totalHour = 0;
							$positionDash = (explode("-", $value['SAL_CODE']));
							$idStaff = '';
							if(is_numeric($positionDash[0])){
								
								$idStaff = $positionDash[0];
								$stfName = trim($positionDash[1]);
								if($idStaff > 0){
									
									if($idStaff != 4 && $idStaff != 165 && $idStaff != 131 && $idStaff != 380){
										$totalHour = $ts->totalWorkingHours($idStaff, $intDateBegin, $intDateEnd,$shop);
										if($totalHour > 0){

											$staffKPI[$shop][$stfName][$v["date_end"]]['hour'] = $totalHour;
											$staffKPI[$shop][$stfName][$v["date_end"]]['amount'] = $value["SALES"];
											$staffKPI[$shop][$stfName][$v["date_end"]]['KPI'] = round($value["SALES"]/$totalHour,2);
										}else{
											$staffKPI[$shop][$stfName][$v["date_end"]]['hour'] = 0;
											$staffKPI[$shop][$stfName][$v["date_end"]]['amount'] = $value["SALES"];
											$staffKPI[$shop][$stfName][$v["date_end"]]['KPI'] = 0;
										}
									}
								}
								
							}

							
					
	
						}
				
				}
				
				
				
			}
			$tmpArr['mon_sum'] = $monthSum; // monthly total
			$tmpArr['target_week'] = $tarLine["target"]/$weeks; // weekly
			$tmpArr['target'] = $tarLine["target"]; // monthly target
			$tmpArr['staff_id'] = $staffID;
			$tmpArr['target_2_week'] = $tarLine["target2"]/$weeks; // weekly2
			$tmpArr['target_2'] = $tarLine["target2"]; // monthly target2
			$tmpArr['target_3_week'] = $tarLine["target3"]/$weeks; // weekly3
			$tmpArr['target_3'] = $tarLine["target3"]; // monthly target3
			// bonus
			$arrRes[] = $tmpArr;             
			

		}
		$this->view->arrWeek = $arrWeeks;
		$this->view->arrRes = $arrRes;
		$this->view->dateBegin = $dateBegin;
		$this->view->dateEnd = $dateEnd;
		
		//d($arrRes);
		
		$this->view->email =  $arrMgrEmail[$idManager];//co1@phonecollection.com.au";
		$this->view->ifemail = $ifEmail;
		$this->view->staffKPI = $staffKPI;
		
	}
	
	/**
	 * this will be send out every day morning to show the manager yesterday's sales result 
	 */
	public function dailyReportManagerAction(){
		
		$idManager = $this->_getParam("mgr");
		$ifEmail = $this->_getParam("email");
		
		$arrMgrEmail = unserialize(ARR_MANAGER_EMAIL);
		
	
		$dateToday = Model_DatetimeHelper::dateToday();

		$dateYesterday = Model_DatetimeHelper::dateYesterday();
		$date2Days = Model_DatetimeHelper::adjustDays("sub", $dateToday,8);
		
		$weekBegin = Model_DatetimeHelper::getThisWeekMonday();
		$weekEnd = Model_DatetimeHelper::getThisWeekSunday();
		
		
		$lastWeekBegin = Model_DatetimeHelper::getLastWeekMonday();
		$lastWeekEnd = Model_DatetimeHelper::getLastWeekSunday();		
		
		
		$caClose = new Model_DbTable_Cashaccountclosing();
		$sf = new Model_DbTable_Target_Shopfomula();
		$tar = new Model_DbTable_Target_Weeklytarget();
		
		
		//$idManager = 4;
		
		//$id = $this->_getParam("mid");
		//$idManager = base64_decode($id);
		$shopList = "";
		
		if($idManager == "all"){
			
			$shopList = array(
					array("shop_code"=>"CBPC","cot"=> "0" ),//hope			
					array("shop_code"=>"PMIC","cot"=> "0"),
					array("shop_code"=>"PMPC","cot"=> "0"),
					array("shop_code"=>"CBIC","cot"=> "0"),
					//Hope 
					array("shop_code"=>"FGIC","cot"=> "1" ),// Adele
					
					array("shop_code"=>"BSIC","cot"=> "0"), // will
					array("shop_code"=>"BSPC","cot"=> "0"),
					array("shop_code"=>"BSXP","cot"=> "0"),
					
					array("shop_code"=>"BHPC","cot"=> "1"),
															// TERRA
					array("shop_code"=>"KCPC","cot"=> "1"),					
					
					
					array("shop_code"=>"BBPC","cot"=> "0"),// no one care
					array("shop_code"=>"HPIC","cot"=> "0"),					
					array("shop_code"=>"SLIC","cot"=> "0"),
					
					//jason 
					array("shop_code"=>"EPIC","cot"=> "1"),
					array("shop_code"=>"NLPC","cot"=> "1"), 
					
					array("shop_code"=>"WGPC","cot"=> "0"),// iris 
					array("shop_code"=>"WGIC","cot"=> "0"),
					
					array("shop_code"=>"WBPC","cot"=> "1"),
					array("shop_code"=>"WBIC","cot"=> "1"), // catherine
					
					array("shop_code"=>"ADPC","cot"=> "0"), // kevin 
					array("shop_code"=>"CLPC","cot"=> "0"),	
					array("shop_code"=>"WLIC","cot"=> "0")
					);
		}
		else{
			$shopList = $sf->listShopByManager($idManager);
		}
		
		
		
		$arrRes = array();
		foreach($shopList as $sp){
			$tmpArr = array();

			$shop = $sp["shop_code"];
			$tmpArr["shop"] = $shop;
			
			$target = $tar->getWeeklyTargetByShopByDate($shop, $dateToday);
			//d($target);
			//$target["target"];
			$week = 0;
			foreach(unserialize(BONUS_CYCLE_2015) as $key => $v){
			
				if($dateToday >= $v[0] && $dateToday <=$v[1]){
						
					$week = ((Model_DatetimeHelper::dateDiff($v[1], $v[0]))+1)/7;
				}
			
			}	
			$weekTarget = Round($target["target"]/$week);
			$weekTarget2 = Round($target["target2"]/$week);
			$weekTarget3 = Round($target["target3"]/$week);
			
			$tmpArr["target"] = $weekTarget;
			$tmpArr["target2"] = $weekTarget2;
			$tmpArr["target3"] = $weekTarget3;
			
			

			
			
			$yesterdaySales = $caClose->getActiveClosingByDate($shop, $dateYesterday);
			//echo $yesterdaySales[0]["apos_sys_sales_total"];
			$tmpArr["yesterday"] =  $yesterdaySales[0]["apos_sys_sales_total"];
			
			$twoDaysBefore = $caClose->getActiveClosingByDate($shop, $date2Days);
			//echo $twoDaysBefore[0]["apos_sys_sales_total"];
			$tmpArr["2days"] = $twoDaysBefore[0]["apos_sys_sales_total"];
			
			$tmpArr["week_total"] = $thisWeekTotal = $caClose->getWeeklyAPOSSummaryShop($shop,$weekBegin, $weekEnd);
			$tmpArr["week_days"] = $thisWeekDays = $caClose->getWeeklyAPOSSummaryShopDays($shop,$weekBegin, $weekEnd);
			$tmpArr["percent"] = $percent = round($thisWeekTotal / $weekTarget,2) *100;
			$tmpArr["remain"]= $remaining = ($thisWeekTotal < $weekTarget)? ($weekTarget - $thisWeekTotal):0;	
			$tmpArr["daily_target"] = $dailyTarget = round($remaining / Model_DatetimeHelper::dayLeft(),0);
			$tmpArr["last_week_total"] = $lastWeekTotal = $caClose->getWeeklyAPOSSummaryShop($shop,$lastWeekBegin,$lastWeekEnd);  
			$tmpArr["last_week_sofar"] = $lastWeekSofar = $caClose->getWeeklyAPOSSummaryShop($shop,$lastWeekBegin,$date2Days);   
			$tmpArr["last_week_precent"] = ($thisWeekTotal >0)? round($lastWeekSofar/$thisWeekTotal*$percent,0):1; 
			
			if($idManager == "all"){
				$tmpArr["color"] = $sp["cot"];
			}
			else{
				$tmpArr["color"] = 0;
			}
			$arrRes[] = $tmpArr;
		}
		
		$this->view->arrRes = $arrRes;
		$this->view->email =  $arrMgrEmail[$idManager];//co1@phonecollection.com.au";
		$this->view->ifemail = $ifEmail;
		/**
		 * Staff issue 
		 */
		

		//attendance missing 
		//attendance late 
		
		
		$attRcord = new Model_DbTable_Roster_Attnrecord();
		$ts = new Model_DbTable_Roster_Timesheet();
		
		$arrMiss = array();
		
		foreach($shopList as $sp){
			
			$shop = $sp["shop_code"];
			$tList = $ts->listShiftByDateByShop($shop,$dateYesterday, $dateYesterday);
			foreach($tList as $timeSheetRow){
				
				
				$idStaff = $timeSheetRow['id_staff'];	
				$rList = $attRcord->getFirstOnLastOffDuty($idStaff, $dateYesterday, Model_EncryptHelper::sslPassword($shop));

				if($rList[0]=="" || $rList[1]==""){
					$timeOn =($rList[0]=="")?"N/A":date("H:i:s",$rList[0]);
					$timeOff =($rList[1]=="")?"N/A":date("H:i:s",$rList[1]);
					$arrMiss[] = array($idStaff,$dateYesterday,$shop,$timeOn,$timeOff);
					
				}
				
		
			}
		}
		
		//var_dump($arrMiss);
		$this->view->arrMiss = $arrMiss;
		
	}

	
	/**
	 * this runs every wednesday from 0 to 8 am
	 * it gives the record of last 8 weeks sales result for all the barocde 
	 * 
	 */
	
	public function lastEightWeeksSalesAction(){
		
		$beginSunday = Model_DatetimeHelper::adjustWeeks("sub",Model_DatetimeHelper::getLastWeekSunday(),7);
		$beginMonday = Model_DatetimeHelper::adjustWeeks("sub",Model_DatetimeHelper::getLastWeekMonday(),7);
		
		$caClosing = new Model_DbTable_Cashaccountclosing();
		
		//$caClosing-
		
		$arrSales = array();
		$shopArr = unserialize(ARR_SHOP_ACTIVE);
		sort($shopArr);
			foreach($shopArr as $shopCode){
				$tmpArr = array();
				//$tmpArr[] = Model_DatetimeHelper::adjustWeeks("add",$beginMonday,$i)." to ".Model_DatetimeHelper::adjustWeeks("add",$beginSunday,$i);
				$tmpArr[] = $shopCode;
				for($i=0; $i<8; $i++){
					
					$tmpArr[] = $caClosing->getWeeklyAPOSSummaryShop($shopCode, Model_DatetimeHelper::adjustWeeks("add",$beginMonday,$i) , Model_DatetimeHelper::adjustWeeks("add",$beginSunday,$i));
				}
				$arrSales[] = $tmpArr;
			}
			
		$this->view->arrSales = $arrSales;
		$this->view->shopArr = $shopArr;
		
		$this->view->beginMonday = $beginMonday;
		$this->view->beginSunday = $beginSunday;
		
		//<>var_dump($arrSales);
		
	}
	
	/**
	 * this is combine in to the shop ranking already 
	 */
	public function repairRankingAction(){
	
		$shopArr = unserialize(ARR_SHOP_ACTIVE);
		
		$lastMonday = Model_DatetimeHelper::getLastWeekMonday();
		$lastSunday = Model_DatetimeHelper::getLastWeekSunday();
		
		$beginMonday = Model_DatetimeHelper::adjustWeeks("sub", $lastMonday,1);
		$beginSunday = Model_DatetimeHelper::adjustWeeks("sub", $lastSunday,1);
		
		$caClosing = new Model_DbTable_Cashaccountclosing(Zend_Registry::get('db_remoteapp'));
		
		$invOld = "";
		$invPro = "";
		
		$arrRes = array();
		$amtRes = array();
		
		$arrTotal = array();
		
		foreach($shopArr as $shop){
			
			$invOld = Model_Aposinitnew::initAposInvoice($shop);
			$invPro = Model_Aposinitnew::initAposInvPro($shop);

			
			
			$repairAmt = $invPro->getRepairTotalByDate($lastMonday, $lastSunday);
			$totalAmt = $caClosing->getWeeklyAPOSSummaryShop($shop, $lastMonday, $lastSunday);
			
			$repairAmtWeekAgo = $invPro->getRepairTotalByDate($beginMonday, $beginSunday);
			$totalAmtWeekAgo = $caClosing->getWeeklyAPOSSummaryShop($shop, $beginMonday, $beginSunday);
			
			if($totalAmt == 0 && $totalAmtWeekAgo == 0){
				$tmpArr = array($shop,$repairAmt,0,$repairAmtWeekAgo,0,0,0);
			}
			elseif($totalAmt == 0 && $totalAmtWeekAgo != 0){
				$tmpArr = array($shop,$repairAmt,0,$repairAmtWeekAgo,$repairAmtWeekAgo/$totalAmtWeekAgo,0,$totalAmtWeekAgo);
			}elseif($totalAmt != 0 && $totalAmtWeekAgo == 0){
				$tmpArr = array($shop,$repairAmt,$repairAmt/$totalAmt,$repairAmtWeekAgo,0,$totalAmt,0);
			}else{
				$tmpArr = array($shop,$repairAmt,$repairAmt/$totalAmt,$repairAmtWeekAgo,$repairAmtWeekAgo/$totalAmtWeekAgo,$totalAmt,$totalAmtWeekAgo);
			}
			
			
			$arrRes[] = $tmpArr;
			$amtRes[] = $repairAmt;
			$arrTotal[] = $totalAmt;
			
			
		}
		
		array_multisort($amtRes,SORT_DESC,$arrRes);
		array_multisort($arrTotal,SORT_DESC,$shopArr);
		
		$this->view->arrRes = $arrRes;
		$this->view->shopArr = $shopArr;
		
		$this->view->strLastWeek = $lastMonday." - ".$lastSunday;
		$this->view->strWeekAgo = $beginMonday." - ".$beginSunday;
		
		//var_dump($arrRes);
	}
	
	/**
	 * check if most shop has the new stock or old stock 
	 */
	public function shopStockAndLocationAction(){
		
		$stk = Model_Aposinitnew::initProStock("WBIC");
		$des = Model_Aposinitnew::initProDes();
		$loc = new Model_Products_Location(Zend_Registry::get('db_remoteapp'));
		$stkList = $stk->listShopHave("WBIC");
		
		$arrRes = array();
		foreach($stkList as $item){
			
			$desLine = $des->getAposDes($item['SCODE']);
			$locLine = $loc->getLocationsByProduct($item['SCODE']);
			$arrLoc = "";
			if($locLine){
			foreach ($locLine as $locItem){
				
				if($locItem['type_location'] == "PL"){
				 $arrLoc = $locItem['code_location'];
				}
			}
			}
			//d($locLine);
			$arrRes[] = array($item['SCODE'],$desLine['DESCRIPT'],$arrLoc);
			
		}
		//d($arrRes);
		$this->view->arrRes = $arrRes;
		
	}

	/**-----------------------------Section Start  Automatic -------------------------------------------**/
	/**
	 * @author Norman
	 * According The introduce date from apos , From title Updateed Date from DB
	 * define if the product title should be what?
	 * *1 to *5 then  #C
	 * run on every monday after work , 
	 */
	public function swapAposTitleByIntroduceDateAction(){
		
		set_time_limit(0);
		
		date_default_timezone_set("Australia/Melbourne");
		
		// apos list all barcode 
		$aPro = Model_Aposinitnew::initProDes();
		$aProNew = Model_Aposinitnew::initProDesNewApos();
		
		$pro = new Model_DbTable_Productsva(Zend_Registry::get('db_remoteapp'));
		$log = new Model_Helperapos_Scodelog(Zend_Registry::get('db_helperapos'));
		$des = Model_Aposinitnew::initProDes();
		// date APOS 
		
		$dbApos = Model_DatetimeHelper::getLastWeekMonday();
		$dnApos = Model_DatetimeHelper::getLastWeekSunday();
		

	
		
	    // plus those starts 
	    // if it *3 and very cold #C to clear it 
		$arrPrepare = array();
	    $doubleStarList = $log->getLastWeekUpdate($dbApos, $dnApos);
		
	    foreach($doubleStarList as $k => $v){
	    	//record update Date today 
	    	$pro->titleUpdateDate(trim($v['SCODE']));
	    }
		//set initial Date 
		
	    $proList = $pro->listAllProducts();
	    $arrCanBeDone = array();
	    d(count($proList));
	    foreach($proList as $key => $v){
	    	
	    	//d($v['code_product']);

	    	if(strpos($v['code_product'],"STA-") === false && strpos($v['code_product'],"STRAP-") === false && strpos($v['code_product'],"SERVICE") === false ){
	    		
	    		$proTitle = $des->getAposDes($v['code_product']);
	    		$proTitle = $proTitle['DESCRIPT'];
	    		
	    		if( strpos($proTitle,'#C') === false && strpos($proTitle,'#C30') === false && strpos($proTitle,'#D') === false){
	    			
	    			$dateUpdate = $v['update_title'];
	    			
	    			$dayDiff = Model_DatetimeHelper::dateDiff($dateUpdate,Model_DatetimeHelper::dateToday());
	    			
	    			// change date 
	    			if(strpos($proTitle,'**') !== false){
	    				$proTitle = str_replace("**", "A0 ", $proTitle);
	    				
	    				if(strlen(trim($proTitle)) > 60){
	    					echo $v['code_product'].",".$proTitle.",".strlen($proTitle)."<br />";
	    				}
	    				else{
	    					$arrCanBeDone[] = $proTitle;
	    					$aPro->updateDes($v['code_product'],$proTitle);
	    					$aProNew->updateDes($v['code_product'],$proTitle);
	    					//$pro->titleUpdateDate($v['code_product'],'2014-09-09');
	    				}
	    			}
	    			
	    			
	    			if($dayDiff == 34 && (strpos($proTitle,'*1') !== false)){
	    				
	    				
	    				
	    				$proTitle = str_replace("*1", "B2", $proTitle);
	    				if(strlen(trim($proTitle)) > 60){
	    					echo $v['code_product'].",".$proTitle.",".strlen($proTitle)."<br />";
	    				}
	    				else{
	    					$arrCanBeDone[] = $proTitle;
	    					$aPro->updateDes($v['code_product'],$proTitle);
	    					$aProNew->updateDes($v['code_product'],$proTitle);
	    					$pro->titleUpdateDate($v['code_product'],'2014-09-09');
	    				}
	    				
	    				
	    			}
	    			if($dayDiff == 28 && (strpos($proTitle,'A1') !== false)){
	    				 
	    				$proTitle = str_replace("A1", "B2", $proTitle);
	    				if(strlen(trim($proTitle)) > 60){
	    					echo $v['code_product'].",".$proTitle.",".strlen($proTitle)."<br />";
	    				}
	    				else{
	    					$arrCanBeDone[] = $proTitle;
	    					$aPro->updateDes($v['code_product'],$proTitle);
	    					$aProNew->updateDes($v['code_product'],$proTitle);
	    					$pro->titleUpdateDate($v['code_product']);
	    				}
	    				 
	    				 
	    			}
	    			if($dayDiff == 28 && (strpos($proTitle,'B2') !== false)){
	    				 
	    				$proTitle = str_replace("B2", "C3", $proTitle);
	    				if(strlen(trim($proTitle)) > 60){
	    					echo $v['code_product'].",".$proTitle.",".strlen($proTitle)."<br />";
	    				}
	    				else{
	    					$arrCanBeDone[] = $proTitle;
	    					$aPro->updateDes($v['code_product'],$proTitle);
	    					$aProNew->updateDes($v['code_product'],$proTitle);
	    					$pro->titleUpdateDate($v['code_product']);
	    				}
	    				 
	    				 
	    			}
	    			// change date , then change today's date to last tuesaday , do it next tuesday
	    			if($dayDiff == 34 && (strpos($proTitle,'*3') !== false)){
	    			
	    				$proTitle = str_replace("*3", "C4", $proTitle);
	    				if(strlen(trim($proTitle)) > 60){
	    					echo $v['code_product'].",".$proTitle.",".strlen($proTitle)."<br />";
	    				}
	    				else{
	    					$arrCanBeDone[] = $proTitle;
	    					$aPro->updateDes($v['code_product'],$proTitle);
	    					$aProNew->updateDes($v['code_product'],$proTitle);
	    					$pro->titleUpdateDate($v['code_product'],'2014-09-09');
	    				}
	    			
	    			
	    			}
	    			
	    			if($dayDiff == 28 && (strpos($proTitle,'C3') !== false)){
	    			
	    				$proTitle = str_replace("C3", "C4", $proTitle);
	    				if(strlen(trim($proTitle)) > 60){
	    					echo $v['code_product'].",".$proTitle.",".strlen($proTitle)."<br />";
	    				}
	    				else{
	    					$arrCanBeDone[] = $proTitle;
	    					$aPro->updateDes($v['code_product'],$proTitle);
	    					$aProNew->updateDes($v['code_product'],$proTitle);
	    					$pro->titleUpdateDate($v['code_product']);
	    				}
	    			
	    			
	    			}
	    			if($dayDiff == 28 && (strpos($proTitle,'C4') !== false)){
	    			
	    				$proTitle = str_replace("C4", "C5", $proTitle);
	    				if(strlen(trim($proTitle)) > 60){
	    					echo $v['code_product'].",".$proTitle.",".strlen($proTitle)."<br />";
	    				}
	    				else{
	    					$arrCanBeDone[] = $proTitle;
	    					$aPro->updateDes($v['code_product'],$proTitle);
	    					$aProNew->updateDes($v['code_product'],$proTitle);
	    					$pro->titleUpdateDate($v['code_product']);
	    				}
	    			
	    			
	    			}
	    			
	    			if($dayDiff == 35 && (strpos('**',$proTitle) !== false)){
	    				 
	    				$proTitle = str_replace("**", "A1", $proTitle);
	    				if(strlen(trim($proTitle)) > 60){
	    					echo $v['code_product'].",".$proTitle.",".strlen($proTitle)."<br />";
	    				}
	    				else{
	    					$arrCanBeDone[] = $proTitle;
	    					$aPro->updateDes($v['code_product'],$proTitle);
	    					$aProNew->updateDes($v['code_product'],$proTitle);
	    					$pro->titleUpdateDate($v['code_product']);
	    				}
	    				 
	    				 
	    			}
	    			/*
	    			if($dayDiff == 28 && (strpos('*1',$proTitle) !== false || strpos('*2',$proTitle) !== false || strpos('*3',$proTitle) !== false  || strpos('*4',$proTitle) !== false )   ){
	    				//  swap title 				
	    				
	    			}
	    			if($dayDiff == 28 && strpos('*5',$proTitle) !== false){
	    				// time to clear it 
	    				
	    			}
	    			if($dayDiff == 35 && strpos('**',$proTitle) !== false){
	    				// * 1 
	    				    
	    			}
	    			*/
	    			
	    		}
	    		else{
	    			// if not freeze set to freeze update the update date 
	    			//echo "Product Title:".$proTitle." Will Set To Freeze: <br />";
	    			if($v['freeze_update']==null){
	    				$pro->freezeUpdate($v['code_product'],1);
	    				$pro->titleUpdateDate($v['code_product']);
	    			}
	    			
	    			
	    		}
	    		
	    	}
	    	
	 
	    }
	 

	    // find all barcode in product DB, check update date 
	    // if the date is 4/ 5 weeks ago find if freeze, if #C ** #D #C30
	    // if 5 weeks -> ** to * 1
	    // if 4 weeks -> *2-> *3 
	    // if 4 week s *5-> do nothing produce List of selection
	    // if > 5 weeks and No freeze give error 
	    // give freeze list 
	    // if Null Ignore  give list 
	    
d($arrCanBeDone);
		

			

	}
	/**
	 * once off function 
	 */
   public function onceOffStarOneStarThreeAction(){
   	
   	set_time_limit(0);
   	
   	date_default_timezone_set("Australia/Melbourne");
   	
   	$aPro = Model_Aposinitnew::initProDes();
   	$aProNew = Model_Aposinitnew::initProDesNewApos();
   	
   	$pro = new Model_DbTable_Productsva(Zend_Registry::get('db_remoteapp'));
   	$log = new Model_Helperapos_Scodelog(Zend_Registry::get('db_helperapos'));
   	
   	$proList = $pro->listAllProducts();
   	$arrCanBeDone = array();
   	 
   	foreach($proList as $key => $v){
   		
   		if(strpos($v['code_product'],"STA-") === false && strpos($v['code_product'],"STRAP-") === false && strpos($v['code_product'],"SERVICE") === false ){
   			 
   			$proTitle = $aPro->getAposDes($v['code_product']);
   			$proTitle = $proTitle['DESCRIPT'];
  
   			if( strpos($proTitle,'#C') === false && strpos($proTitle,'#C30') === false && strpos($proTitle,'#D') === false && strlen(trim($proTitle)) >0){
   			
   				if( strpos($proTitle,'**') !== false){
   					
   					if($v['update_title'] == ""){
   					$proTitle = str_replace("**", "*1 ", $proTitle);
   					//echo $proTitle."[".strlen($proTitle)."]<br />";
   					if(strlen(trim($proTitle)) > 60){
   						echo $v['code_product'].",".$proTitle.",".strlen($proTitle)."<br />";
   					}
   					else{
   						$arrCanBeDone[] = $proTitle;
   						//$aPro->updateDes($v['code_product'],$proTitle);
   						//$aProNew->updateDes($v['code_product'],$proTitle);
   						$pro->titleUpdateDate($v['code_product']);
   					}
   					}
   				}
   				else{
   					// normal title 
   					if($v['update_title'] == ""){
   						$proTitle = "*3 ".$proTitle;
   						if(strlen(trim($proTitle)) > 60 ){
   								
   							echo $v['code_product'].",".$proTitle.",".strlen($proTitle)."<br />";
   						}
   						else{
   							$arrCanBeDone[] = $proTitle;
   							$aPro->updateDes($v['code_product'],$proTitle);
   							$aProNew->updateDes($v['code_product'],$proTitle);
   							$pro->titleUpdateDate($v['code_product']);
   						}
   					}
   					
   				}
   				
   				
   				
   			}
   			
   			
   		}	
   	}
   	
   	
   	d($arrCanBeDone);
   }
   
   /*---------------------------- Section Start Shop Password On CIP / Reset -------------------------------*/
	/**
	 * Show and Disable (Every Day) Password on Yesterday Summary page
	 */
	public function showPasswordInfoPageAction(){
		
		$sp = new Model_DbTable_Shoplocation();
		$shop = $this->_getParam("shop");
		$sp->copyPass($shop);
		echo "Password Set To Info Page Done!";
	}	
	/**
	 * Reset Password Every day night 
	 */
	public function resetPasswordInfoPageAction(){
		$arrShop = unserialize(ARR_SHOP);
		$sp = new Model_DbTable_Shoplocation();
		foreach($arrShop as $shop){
			$sp->copyPass($shop,'YES');
			
			echo "RESET Password DONE";
		}
		
	}
	/*---------------------------- Section End Shop Password On CIP / Reset -------------------------------*/	
	
	private function whichCircle($dateToCheck){
		
		$intDate = Model_DatetimeHelper::tranferToInt($dateToCheck);
		
		foreach(self::$targetCycle as $key => $v){
			
			$intBegin = Model_DatetimeHelper::tranferToInt($v[0]);
			$intEnd = Model_DatetimeHelper::tranferToInt($v[1]);
			
			if($intDate >= $intBegin && $intDate <= $intEnd ){
				
				return $v;
				
			}
			
			
		}
		
		return false;
		
	}
	
	/**
	 * Every Two Weeks , generate a report base on KT 
	 * Report Generate on Monday Morning , put in to genearte order process (Manual add a Hint)
	 * Waiting for recalculate ,then when begin to generate order , provide the report 
	 * 
	 */
	
	public function shopOverStockPrepareAction(){
		
		$ktNo = $this->_getParam("kt_no");
		
		$shop = $this->_getParam("shop");
		
		
	}
	
	public function shopOverStockReportAction(){
		
		$ktNo = $this->_getParam("kt_no");
		
		$shop = $this->_getParam("shop");
		$email = $this->_getParam("email");
		
		$aKt = Model_Aposinitnew::initKtData($shop);
		$invPro = Model_Aposinitnew::initAposInvPro($shop);
		$arrShop = unserialize(ARR_APOS_NEW_SHOP_MAPPING);
		$kList = $aKt->listKT($ktNo,$arrShop[$shop]);
		$stock = Model_Aposinitnew::initProStock($shop);
		$des = Model_Aposinitnew::initProDes();
		
		$order = new Model_DbTable_Order_Weeklyorder(Zend_Registry::get('db_remoteapp'));
		
		$mondayTwoWeekAgo = Model_DatetimeHelper::adjustWeeks("sub",Model_DatetimeHelper::getLastWeekMonday(),1,"");
		
		$noOrder = "PD".$shop.$mondayTwoWeekAgo;
		//d($kList);
		$monday1W = Model_DatetimeHelper::getLastWeekMonday();
		$sunday1W = Model_DatetimeHelper::getLastWeekSunday();
		
		$monday2W = Model_DatetimeHelper::adjustWeeks("sub",$monday1W,1);
		$sunday2W = Model_DatetimeHelper::adjustWeeks("sub",$sunday1W,1);
		
		$totalOverStock = 0;

		$arrRes = array();
		foreach($kList as $kLine){
			$sCode = trim($kLine['SCODE']);
			$orderLine = $order->barcodeExistInOrder($sCode, $noOrder);
			$orgQty = 0;
			if($orderLine){
				$orgQty = $orderLine['qty_order'];
			}
			$desc = $des->getAposDes($sCode);
			$sales1W = $invPro->getProductSalesQtyByDates($monday1W, $sunday1W, $sCode);
			$sales2W = $invPro->getProductSalesQtyByDates($monday2W, $sunday2W, $sCode);
				
			$arrcSk = $stock->getStockBalance($sCode,$arrShop[$shop]);
			$cStock = $arrcSk['BALANCE'];
				
			$overStock = '';
			$overStockTitle = '';
			
			if(($sales1W + $sales2W) == 0){
				$isFirst = $aKt->isFirstKt($sCode,$arrShop[$shop], $ktNo);
				if(!$isFirst){	
				$overStock = 1;
				$overStockTitle = 'YES';
				$totalOverStock++;
				}
				else{
				
					$overStockTitle = '*(New)';
					
				}
			}else{
				if(($cStock/($sales1W + $sales2W)) > 2){
					$overStock = 1;
					$overStockTitle = 'YES';
					$totalOverStock++;
				}
			}
				
				
			$arrRes[] = array($sCode,$desc['DESCRIPT'],$sales1W,$sales2W,(($sales1W + $sales2W)>0)?round($cStock/($sales1W + $sales2W),1):'&infin;',$overStockTitle,(int)$kLine['QTY'],$orgQty);
		}
		$this->view->arrRes = $arrRes;
		$this->view->totalOverStock = round($totalOverStock/count($arrRes)*100,2);
		$this->view->ktNo = $ktNo;
		
	}
	
	
}
?>